package com.fxwater.admin.controller.biz;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fxwater.common.core.controller.BaseController;
import com.fxwater.common.core.domain.AjaxResult;
import com.fxwater.common.utils.Base64;
import com.fxwater.common.utils.FaceTool;
import com.fxwater.common.utils.StringUtils;

//import sun.misc.BASE64Encoder;

/**
 * 文件上传
 * @author tx
 *
 */
@Controller
@RequestMapping("/biz/file")
public class FileUploadController extends BaseController {
	
	@RequestMapping("/imgUpload")
	@ResponseBody
	public AjaxResult addSave(@RequestParam("file") MultipartFile file) throws IOException
	{
	    if( !file.isEmpty() ) {
	        String data = new String(Base64.encodeBase64(file.getBytes()));
	    	AjaxResult res = AjaxResult.success();
	        res.put("url", data);
	        
	        // 获取文件名
	        String fileName = file.getOriginalFilename();
	        // 获取文件后缀
	        String prefix=fileName.substring(fileName.lastIndexOf("."));
	        // 用uuid作为文件名，防止生成的临时文件重复
	        final File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), prefix);
	        // MultipartFile to File
	        file.transferTo(excelFile);
	        String face_token = null;
	        String result = FaceTool.getResult(excelFile);
	        if(!StringUtils.isEmpty(result)) {
	        	JSONObject rjo = JSONObject.parseObject(result);
	        	JSONArray facesJa =  rjo.containsKey("faces")?rjo.getJSONArray("faces"):null;
	        	if( facesJa != null && facesJa.size() > 0 ) {
	        		face_token = facesJa.getJSONObject(0).containsKey("face_token")?facesJa.getJSONObject(0).getString("face_token"):null;
	        		 res.put("faceToken", face_token);
	        		 
	        		 String isFaceSetExits = FaceTool.getFaceDetail(null);
	        		 if(StringUtils.isEmpty(isFaceSetExits)) {
	        			 //创建
	        			FaceTool.createFaceSetToken();
	        		 }
	        		 FaceTool.addFaceSetToken(face_token);
	        		 
	        	}
	        	
	        }	
	        
	        //程序结束时，删除临时文件
	        deleteFile(excelFile);
	        return res;
	    }
	    return error("上传失败");
	}

	
	/**  
     * 删除  
     *   
     * @param files  
     */  
    private void deleteFile(File... files) {  
        for (File file : files) {  
            if (file.exists()) {  
                file.delete();  
            }  
        }  
    }
	
}
